package cn.chiship.sdk.core.util;

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * XML工具
 *
 * @author lijian
 */
public class XmlUtil {

	/**
	 * request参数转换map对象
	 * @param request request请求
	 * @return Map对象
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String, Object> parseXML(HttpServletRequest request) throws IOException, DocumentException {
		Map<String, Object> map = new HashMap<String, Object>();
		SAXReader reader = new SAXReader();
		Document doc = reader.read(request.getInputStream());
		Element root = doc.getRootElement();
		recursiveParseXML(root, map);
		return map;
	}

	private static void recursiveParseXML(Element root, Map<String, Object> map) {
		List<Element> elementList = root.elements();
		if (elementList.size() == 0) {
			map.put(root.getName(), root.getTextTrim());
		}
		else {
			for (Element e : elementList) {
				recursiveParseXML(e, map);
			}
		}
	}

	/**
	 * xml字符串转换map对象
	 * @param strxml 字符串
	 * @return map对象
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static SortedMap<String, Object> parseXML(String strxml) throws DocumentException, IOException {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
		if (null == strxml || "".equals(strxml)) {
			return null;
		}
		SortedMap<String, Object> map = new TreeMap<String, Object>();
		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXReader reader = new SAXReader();
		Document document = reader.read(in);
		Element root = document.getRootElement();
		List<Element> elements = root.elements();
		for (Element element : elements) {
			map.put(element.getName(), element.getText().trim());
		}
		// 关闭流
		in.close();
		return map;
	}

	/**
	 * 将java类转xml 使用注解：@XStreamAlias("xml")
	 * @param obj
	 * @return String
	 */
	public static String toXml(Object obj) {
		XStream xstream = new XStream();
		xstream.processAnnotations(obj.getClass());
		return xstream.toXML(obj);
	}

}
